package com.xzzz.common.base.api.permenv;

import cn.hutool.core.util.ArrayUtil;
import com.xzzz.common.base.exception.XzException403;
import com.xzzz.common.base.pojo.RCode;
import com.xzzz.common.base.util.spring.SpringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;

@Aspect
@Order(-100)
public class PermEnvAspect implements EnvironmentAware {

    private String envName;

    @Override
    public void setEnvironment(Environment environment) {
        this.envName = environment.getProperty(SpringUtil.PROFILE_ACTION);
    }

    /**
     * 上下文中检查是否具有对应权限
     *
     * @param joinPoint 切入点调用
     * @param permEnv   方法注解
     * @return
     */
    @Around("@annotation(permEnv)")
    private Object around(ProceedingJoinPoint joinPoint, PermEnv permEnv) throws Throwable {
        String[] envNames = permEnv.denied();

        if (ArrayUtil.isNotEmpty(envNames)) {
            if (ArrayUtil.contains(envNames, envName)) {
                throw new XzException403(RCode.SERVER_DENIED_CUR_ENV.getMsg());
            }
        }

        return joinPoint.proceed(joinPoint.getArgs());
    }
}
